package com.zhu.storesmanager.network;

import com.zhu.storesmanager.R;
import com.zhu.storesmanager.models.SyncModel;
import com.zhu.storesmanager.models.SyncModel.ResultStatus;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.DatabaseUtil;
import com.zhu.storesmanager.utils.Log;
import com.zhu.storesmanager.utils.SalesData;
import com.zhu.storesmanager.views.SyncView;

import android.content.Context;
import android.database.Cursor;
import android.os.Handler;

/**
 * 上传督导拜访数据
 */
public class PutSupervisorVisitData {

	public static final int SYNC_FAILEDEND = 0; //上传失败
	public static final int SYNC_SUCCESSEND = 1; //上传成功

	//上传步骤
	private static final int SETUP_PUTVISITINFO = 1; //上报签入数据
	private static final int SETUP_PUTVISITCONTENT= 2; //上报拜访内容数据

	private Context mContext; //上下文
	private Handler mHandler = null; //消息处理Handler
	private int mConnectStep = -1; //当前同步到第几阶段
	private int retryCount = 0; //重试次数

	//同步结果数据
	private SupervisorData mSupervisorData = null;
	private int mCheckIndex = 0;
	private int mCheckContentIndex = 0;
	private int mVisitId = -1;

	/**
	 * 构造函数
	 * @param context 上下文
	 * @param handler 消息处理Handler
	 */
	public PutSupervisorVisitData(Context context, Handler handler){
		mContext = context;
		mHandler = handler;
	}

	/**
	 * 开始同步
	 * @param visitId 拜访任务ID
	 */
	public void startSync(int visitId){
		mConnectStep = -1;
		retryCount = 0;
		mCheckIndex = 0;
		mCheckContentIndex = 0;
		mVisitId = visitId;
		resetData();
		putSvVisitInfo();
	}

	 /**
     * 重试连接
     */
    private void retryConnect(){
    	switch(mConnectStep){
            case SETUP_PUTVISITINFO:
            	putSvVisitInfo();
                break;
            case SETUP_PUTVISITCONTENT:
            	putVisitContent();
                break;
    	}
    }

    /**
     * 上传拜访信息数据
     */
    private void putSvVisitInfo(){
    	if(mSupervisorData == null){ //加在督导拜访数据
    		mSupervisorData = new SupervisorData(mContext, mVisitId);
    		mSupervisorData.parseData();
    	}
    	mConnectStep = SETUP_PUTVISITINFO;
    	if(mCheckIndex < mSupervisorData.getVisitCheckSize()){
    		String putContent = mSupervisorData.getPutVisitCheckContent(mCheckIndex);
        	if(putContent == null){
        		mCheckIndex++;
        		putSvVisitInfo();
        		return;
        	}
        	new HttpConnectionMethod(new NetworkCallback(){
                public void callFinished(int status, Object result) {
                    // TODO Auto-generated method stub
                	final SyncModel.ResultStatus parseresult = ParseNetworkData.parseResultStatus(result);
                	if(parseresult != null && (parseresult.Status == SyncModel.SUCCEED || parseresult.Status == SyncModel.SUCCEED_PUTTED)){
                		Log.d("putSvVisitInfo=" + parseresult.Msg);
                		showErrorMsg(parseresult.Status, parseresult.Msg);
                		retryCount = 0;
                		mCheckIndex++;
                		putSvVisitInfo();
                	}else{
                	    doRequestError(parseresult);
                	}
                }
             }
            ).callPost(HttpUtil.getPutVisitCheckUrl(), putContent);
    	}else{
    		mHandler.sendEmptyMessage(SyncView.SYNC_6);
    		putVisitContent();
    	}
    }

    /**
     * 上传拜访任务数据
     */
    private void putVisitContent(){
    	mConnectStep = SETUP_PUTVISITCONTENT;
    	if(mCheckContentIndex < mSupervisorData.getVisitContentSize()){
    		String putContent = mSupervisorData.getPutVisitContent(mCheckContentIndex);
        	if(putContent == null){
        		mCheckContentIndex++;
        		putVisitContent();
        		return;
        	}
        	new HttpConnectionMethod(new NetworkCallback(){
                public void callFinished(int status, Object result) {
                    // TODO Auto-generated method stub
                	final SyncModel.ResultStatus parseresult = ParseNetworkData.parseResultStatus(result);
                	if(parseresult != null && (parseresult.Status == SyncModel.SUCCEED || parseresult.Status == SyncModel.SUCCEED_PUTTED)){
                		Log.d("putVisitContent=" + parseresult.Msg);
                		showErrorMsg(parseresult.Status, parseresult.Msg);
                		retryCount = 0;
                		mCheckContentIndex++;
                		putVisitContent();
                	}else{
                	    doRequestError(parseresult);
                	}
                }
             }
            ).callPost(HttpUtil.getPutVisitContentUrl(), putContent);
    	}else{
    		syncSuccessEnd();
    	}
    }

    /**
     * 同步失败
     * @param status 状态
     * @param msg 失败消息
     */
    private void syncFail(int status, String msg){
        Log.e("syncFail="+mConnectStep);
    	if(retryCount < 3){
    		retryCount++;
    		retryConnect();
    	}else{
    		retryCount = 0;
    		mConnectStep = -1;
    		mHandler.sendEmptyMessage(SYNC_FAILEDEND);
    		showErrorMsg(status, msg);
    	}
    }

    /**
     * 同步完成
     */
    private void syncSuccessEnd(){
        deletePutedData();
    	saveSyncData();
    	mConnectStep = -1;
    	retryCount = 0;
    	mHandler.sendEmptyMessage(SYNC_SUCCESSEND);
    	Log.e("syncSuccessEnd");
    }

    /**
     * 删除已上传数据
     */
    private void deletePutedData(){
    	if(mSupervisorData != null){
        	mSupervisorData.updatePutedData();
    	}
    }

    /**
     * 保存同步成功之后的数据
     */
    private void saveSyncData(){
    	mSupervisorData.savePutSuccess();
    }

	/**
	 * 重置数据
	 */
	private void resetData(){
		if(mSupervisorData != null){
        	mSupervisorData.resetData();
        	mSupervisorData = null;
        }
	}
	
	/**
	 * 数据清理
	 */
	public void detory(){
		if(mSupervisorData != null){
        	mSupervisorData.resetData();
        	mSupervisorData = null;
        }
	}

	/**
	 * 处理请求错误消息
	 */
	private void doRequestError(ResultStatus resultStatus){
	    String msg = null;
        int statusfail = 0;
        if(resultStatus == null){ //网络出现错误
            statusfail = SyncModel.FAIL_NETWORK; 
            msg = mContext.getString(R.string.network_fail);
        }else{ //数据出错
            statusfail = resultStatus.Status;
            msg = resultStatus.Msg;
        }
        syncFail(statusfail, msg);
	}

	/**
	 * 显示错误信息
	 * @param status 状态
	 * @param msg 错误消息
	 */
	private void showErrorMsg(int status, final String msg){
	    if(status == SyncModel.FAIL_DATA
	            || status == SyncModel.SUCCEED_PUTTED
	            || status == SyncModel.FAIL_DATA){
	        mHandler.post(new Runnable() {
	            @Override
	            public void run() {
	                // TODO Auto-generated method stub
	                Actions.toastShort(mContext, msg);
	            }
	        });
	    }
	}
}
